# from deepseek

from scapy.all import *
from scapy.layers.inet import TCP
from datetime import datetime

def parse_redis_command(payload):
    """解析 RESP 协议格式的 Redis 命令"""
    try:
        parts = payload.split('\r\n')
        cmd = []
        for part in parts:
            if part and not part.startswith(('*', '$')):
                cmd.append(part)
        return ' '.join(cmd) if cmd else None
    except:
        return None

def extract_redis_full(pcap_file):
    """提取 Redis 命令、时间戳、客户端 IP 和端口"""
    packets = rdpcap(pcap_file)
    results = []
    
    for pkt in packets:
        if pkt.haslayer(TCP) and pkt[TCP].dport == 6379:  # 目标端口是 Redis
            # 提取客户端信息（源 IP 和端口）
            client_ip = pkt[IP].src if pkt.haslayer(IP) else "N/A"
            client_port = pkt[TCP].sport
            
            # 提取时间戳（精确到微秒）
            timestamp = datetime.fromtimestamp(pkt.time).strftime('%Y-%m-%d %H:%M:%S.%f')
            
            # 解析 Redis 命令
            payload = str(pkt[TCP].payload)
            cmd = parse_redis_command(payload)
            
            if cmd:
                results.append({
                    'timestamp': timestamp,
                    'client_ip': client_ip,
                    'client_port': client_port,
                    'command': cmd
                })
    
    return results

# 使用示例
results = extract_redis_full("redis_traffic.pcap")
for item in results:
    print(
        f"[{item['timestamp']}] "
        f"Client {item['client_ip']}:{item['client_port']} -> "
        f"Redis Command: {item['command']}"
    )
